//
//  CityView.m
//  CarHome
//
//  Created by 张世琦 on 14-9-23.
//  Copyright (c) 2014年 WJN_work@163.com. All rights reserved.
//

#import "CityView.h"
#import "ProvincesModel.h"
#import "CitysModel.h"
#import "MunicipalityView.h"

NSString *const cityCell = @"cellId";
#define CENTER 160

@implementation CityView

- (void)dealloc
{
    [_cityArray release];
    [_titleArray release];
    _titleArray = nil;
    _cityArray = nil;
    [super dealloc];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor clearColor];
        _cityArray = [[NSMutableArray alloc] init];
        _titleArray = [[NSMutableArray alloc] init];
        [self createButton];
        [self connect];
        UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc]
                                                        initWithTarget:self
                                                        action:@selector(handlePan:)];
        [self addGestureRecognizer:panGestureRecognizer];
        [panGestureRecognizer release];
    }
    return self;
}

#pragma mark -
#pragma mark 右侧透明button

- (void)createButton
{
    _button = [UIButton buttonWithType:UIButtonTypeCustom];
    [_button setFrame:CGRectMake(0, 0, 80, self.frame.size.height)];
    [_button setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5]];
    [_button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_button];
}

- (void)buttonAction:(id)sender
{
    [self removeFromSuperview];
}

#pragma mark -
#pragma mark 滑动手势

-(void) handlePan:(UIPanGestureRecognizer*) recognizer
{
    CGPoint point = [recognizer translationInView:self];
    float x = self.center.x + point.x;
    _button.backgroundColor = [UIColor clearColor];
    if (x < CENTER) {
        x = self.center.x;
    }
    self.center = CGPointMake(x, self.center.y);
    if(recognizer.state == UIGestureRecognizerStateEnded)
    {
        [UIView animateWithDuration:1
                              delay:0.01
                            options:UIViewAnimationCurveEaseInOut
                         animations:^{
                             if (x > 250) {
                                 self.center = CGPointMake(400, self.center.y);
                             } else {
                                 self.center = CGPointMake(CENTER, self.center.y);
                                 _button.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
                             }
                         } completion:^(BOOL finished) {
                             
                         }];
    }
    [recognizer setTranslation:CGPointZero inView:self];
}


#pragma mark -
#pragma mark 创建TableView

- (void)createTableView
{
    UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(80, 0, 240, self.frame.size.height - 20)];
    aView .backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
    UIView *bView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 240, 44)];
    bView.backgroundColor = [UIColor whiteColor];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(80, 0, 80, 44)];
    label.text = @"选择省份";
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(190, 0, 50, 44)];
    [button setTitle:@"关闭" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [bView addSubview:button];
    [bView addSubview:label];
    [aView addSubview:bView];
    UIButton *all = [UIButton buttonWithType:UIButtonTypeCustom];
    [all setFrame:CGRectMake(0, 0, 320, 40)];
    [all setTitle:@"全国" forState:UIControlStateNormal];
    [all setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [all addTarget:self action:@selector(allAction:) forControlEvents:UIControlEventTouchUpInside];
    _table = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, 240, self.frame.size.height - 134) style:UITableViewStylePlain];
    _table.tableHeaderView = all;
    [_table registerClass:[UITableViewCell class] forCellReuseIdentifier:cityCell];
    _table.dataSource = self;
    _table.delegate = self;
    [aView addSubview:_table];
    [self addSubview:aView];
    
}

- (void)allAction:(id)sender
{
    self.block();
}

#pragma mark -
#pragma mark UITableViewDataSource协议

//每个section行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[_cityArray objectAtIndex:section] count];
}

//重用机制
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cityCell forIndexPath:indexPath];
    [cell.textLabel setText:[[[_cityArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"name"]];
    return cell;
}

//section数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_cityArray count];
}

//section标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *str = [_titleArray objectAtIndex:section];
    return str;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < 26; i++) {
        NSString *str = [NSString stringWithFormat:@"%c", (65 + i)];
        [arr addObject:str];
    }
    return arr;
}

#pragma mark -
#pragma mark UITableViewDelegate协议

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    MunicipalityView *aView = [[MunicipalityView alloc] initWithFrame:CGRectMake(80, 0, 240, self.frame.size.height + 64 + 49)];
    [aView.array addObjectsFromArray:[[[_cityArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"citys"]];
    aView.provinceId = [[[[_cityArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"id"] intValue];
    [self addSubview:aView];
    [aView release];
}

#pragma mark -
#pragma mark 网络请求

- (void)connect
{
    [NetUrl connect:CityURL parmater:nil Block:^(NSData *data) {
        NSMutableDictionary *dic = (NSMutableDictionary *)data;
        NSMutableDictionary *result = [dic objectForKey:@"result"];
        NSMutableArray *provinces = [result objectForKey:@"provinces"];
        for (NSMutableDictionary *dic in provinces) {
            ProvincesModel *model = [[ProvincesModel alloc] init];
            model.firstletter = [dic objectForKey:@"firstletter"];
            model.name = [dic objectForKey:@"name"];
            [_titleArray addObject:model.firstletter];
            NSMutableArray *citys = [dic objectForKey:@"citys"];
            for (NSMutableDictionary *dic in citys) {
                CitysModel *city = [[CitysModel alloc] init];
                city.citysName = [dic objectForKey:@"name"];
                [model.citys  addObject:city];
                [city release];
                }
            }
        NSSet *set = [NSSet setWithArray:_titleArray];
        _titleArray = (NSMutableArray *)[set allObjects];
        _titleArray = [_titleArray sortedArrayUsingSelector:@selector(compare:)];
        [_titleArray retain];
        for (int i = 0; i < [_titleArray count]; i++) {
            NSMutableArray *array = [[NSMutableArray alloc] init];
            [_cityArray addObject:array];
            [array release];
        }
        for (NSDictionary *dic in provinces) {
            [[_cityArray objectAtIndex:[_titleArray indexOfObject:[dic objectForKey:@"firstletter"]]] addObject:dic];
        }
        [self createTableView];
        [_table reloadData];
    }];
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
